import { useDictionary, useSimpleMemo } from '@/components';
import { Select } from 'antd';
import * as PropTypes from 'prop-types';
import React, { forwardRef } from 'react';

/** 基于字典的选项组件 */
function DictSelect(props, ref) {
  const {
    component: Comp = Select,
    code,
    noCache = false,
    hides = [],
    format,
    optionsProp = 'options',
    ...selectProps
  } = props;

  const dictData = useDictionary(code, noCache, format);
  const options = useSimpleMemo(dictData.filter((v) => !hides.includes(v.value)));

  return <Comp ref={ref} {...selectProps} {...{ [optionsProp]: options }} />;
}

DictSelect = forwardRef(DictSelect);

DictSelect.propTypes = {
  /** 字典code */
  code: PropTypes.string.isRequired,

  /** 是否获取新的字典 */
  noCache: PropTypes.bool,

  /** 隐藏的code选项 */
  hides: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.string, PropTypes.number])),

  /** 额外的选项 */
  options: PropTypes.arrayOf(
    PropTypes.shape({
      value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
      label: PropTypes.node,
    }),
  ),

  /** 渲染Select的组件，默认antd/Select */
  component: PropTypes.elementType,
};

export default DictSelect;
